var AV = require('leanengine');
var moment = require('moment');
var redisClient = require('./redisConn');
var Promise = require('bluebird');
var _ = require('underscore');



//定时任务测试
AV.Cloud.define('updateScore', function(request, response) {
var query =  new AV.Query(AV.User);
query.lessThanOrEqualTo('princessNum', 15);
query.count().then(function(count) {
  // 成功了
  console.log('LeanCloud官方客服 发布了 ' + count + ' 条微博');
}, function(error) {
  // 失败了
});
})

//定时任务：每隔10分钟进行一次角色信息查询。如果长时间没有在线的。进行存储并且清理掉
AV.Cloud.define('JudgeHeartbeat', function(request, response) {
	var avObjectArray = [];
	var n=0;
	redisClient.smembersAsync("userIds").then(function(idsStrs){
	console.log('userIds    ......... length '+idsStrs.length);	
		var promise = AV.Promise.as();
		_.each(idsStrs, function(cacheId){	
			promise = promise.then(function(){
				redisClient.getAsync(cacheId).then(function(cachedData) {
					if (cachedData) {
						  // 反序列化为 AV.Object	  
						  var newObj=new AV.User(JSON.parse(cachedData), {parse: true});
						  var updatedAt =newObj.updatedAt;
						  var onLine=newObj.get("onLine");						  
						  
						  var myDate = new Date();							
							var t_s=myDate.getTime();//转化为时间戳毫秒数
							var beforeDate=new Date();//定义一个新时间
							beforeDate.setTime(t_s-1000*60*10);// 设置十分钟前
							console.log(newObj.id+":  "+ updatedAt.getTime()+'  |'+beforeDate.getTime()+"   "+onLine );
						  if(updatedAt.getTime()<beforeDate.getTime()||onLine===false){
								console.log('clean   ************************     ' );
								newObj.set("onLine",false);
								newObj.save().then(function(){
									redisClient.srem("userIds",cacheId );//删除集合元素
									redisClient.delAsync(cacheId); //删除redis数据
									console.log('clean   ************************  1111   '+ cacheId);								
								});
										
						  }
						  //获得世界当前激活的。更新时间较近的玩家信息。过期的被认为是已经下线了。
					}
					else{		
						console.log('clean ******************* ');
						redisClient.sremAsync("mapIds",cacheId);
						}
						
				});
			});	
		});
		return promise;
	
	}).then(function(){
				response.success(true);
			//AV.Object.saveAll(avObjectArray).then(function (avobjs) {
			  //}, function (error) {
			  //});
		
		});	

	
	


})

//心跳回应。设置当前角色在线。每过一分钟进行一次
AV.Cloud.define('Heartbeat', function(request, response) {
	console.log('Heartbeat ******************* '+request.params.id);
	var cacheId=redisUserKey( request.params.id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
		if (cachedData) {
		  // 反序列化为 AV.Object	  
			  var newObj=new AV.User(JSON.parse(cachedData), {parse: true});
			  newObj.set("onLine",true);
			   newObj.updatedAt=new Date();
			  redisClient.setAsync(cacheId, JSON.stringify(newObj)).then(function(){
			  response.success(1);		  
			  }).catch(console.error);
		  }
		  else{
			var paramsJson = {id:request.params.id};
			AV.Cloud.run('GetUser', paramsJson, {
			  success: function(data) {
			  var shieldFailureDate=data.get("shieldFailureDate");
			  var now = new Date();
			  var timeDif=now.getTime()-shieldFailureDate.getTime();
			  if(timeDif<120000&&timeDif>0){
				response.success(0);
			  }else
				response.success(1);
			  },
			  error: function(err) { }
			});
		  }//如果当前没有，直接取数据库。如果发现护盾刚生效并且在120秒内。说明正在被劫掠，需要等待对方抢完
		  
	});


})


//
//获取抢夺列表
AV.Cloud.define('GetRobList', function(request, response) {
var isTest=request.params.isTest;
console.log('GetRobList  ************************     ' );

if(isTest){
    var query = new AV.Query(AV.User);
    query.equalTo('ID', 100);
    query.find({
    success: function(results) {
        var n=0;
        var ids='';
        for (var i = 0; i < results.length; ++i) {
            ids+=(results[i].id);
            //console.log('******************ids   :'+ids );
        }
        response.success(ids);
    },
    error: function() {
      response.error('搜索失败');
    }
  });
    
}//测试，只使用100号用户数据
else
{
    var query = new AV.Query(AV.User);
    var now=new Date();
    query.limit(20);// 最多返回 10 条结果
    query.lessThan('shieldFailureDate',now);// 防御失效之前
    query.addAscending('updatedAt');//按更新时间降序

    query.find({
    success: function(results) {
        var n=0;
        var ids='';
         for (var i = 0; i < results.length; ++i) {
            //console.log('updateAt:'+results[i].get('shieldFailureDate') );
            if(i%3===0&&i<results.length-2){
                var index =fRandomBy(i,i+2);
                ids+=(','+results[i].id);
                //console.log('princessIndex:'+results[i].get('princessIndex') );
            }
        }
        
        response.success(ids);
    },
    error: function() {
      response.error('搜索失败');
    }
  }); 

    
}



  
function fRandomBy(under, over){ 
    switch(arguments.length){ 
    case 1: return parseInt(Math.random()*under+1); 
    case 2: return parseInt(Math.random()*(over-under+1) + under); 
    default: return 0; 
    } 
} 
  
})

//抢夺同时修改被抢者的护盾时间
AV.Cloud.define('OnRob', function(request, response) {
	var robedUserId=request.params.robedUserId;
	query1.get(robedUserId).then(function(robedUser) {
			var myDate = new Date();            
            var t_s=myDate.getTime();//转化为时间戳毫秒数
            var failureDate=new Date();//定义一个新时间
            failureDate.setTime(t_s+1000*60*60*24);//设置新时间比旧时间多一天
			
			robedUser.set('shieldFailureDate',failureDate);
			robedUser.save();
			response.success(true);
	});

})


////////
//抢夺结算
AV.Cloud.define('RobClearing', function(request, response) {
console.log('RobClearing ...................................... ');
var roberId=request.params.roberId;
var robedUserId=request.params.robedUserId;
var robedOpponent=request.params.robedOpponent;
var robAgeinPay=request.params.robAgeinPay;
var isRober=request.params.isRober;

//console.log('roberId: '+ roberId+',  robedOpponent: '+ robedOpponent
//+',  robedUserId: '+ robedUserId+',  robAgeinPay: '+ robAgeinPay+',  isRober: '+ isRober);

if(robedOpponent!==""){
    if(!isRober){
        var query1 = new AV.Query(AV.User);
        query1.get(robedUserId).then(function(robedUser) {
        var  harmOpponentList=robedUser.get('harmOpponentList');
        //更新玩家后宫数据
        if(typeof(harmOpponentList) !== "undefined"&&harmOpponentList!==""){
			var opponents=harmOpponentList.split("*");
			var newList="";
			for(var i=0;i<opponents.length;i++){
				var v=opponents.split(",");
				if(robedOpponent.match(v[0])!==null)
					newList+=("*"+opponents);
			}//获得非抢劫的公主的其他的角色的数据
			if(newList.substring(0, 1) == "*")
                newList= newList.substring(1); 
			
			robedUser.set('harmOpponentList',newList);//设置新的后宫公主怪数据
            robedUser.set('robedPrincess',robedOpponent);//被抢公主
            
            robedUser.save();
        }
        //console.log('修改被抢劫者信息 robedPrincessId: '+ robedUser.get('shieldFailureDate'));
    
        }, function (error) {
      });
        
    }
    //修改被抢者信息
    else{
        
        console.log('修改抢夺者数据  ................... '+robedOpponent);
        var query2 = new AV.Query(AV.User);
        query2.get(roberId).then(function(post) {
			var  harmOpponentList=post.get('harmOpponentList'); 
			harmOpponentList+="*"+robedOpponent;
			
			if(harmOpponentList.substring(0, 1) == "*")
				harmOpponentList= harmOpponentList.substring(1);
				
			post.set('harmOpponentList',harmOpponentList);
			post.save();
			//console.log('修改抢夺者数据  harmOpponentList: '+ harmOpponentList);
			response.success(harmOpponentList);
        }, function (error) {
      });
        //
        
    }
    //修改抢夺者自己的数据
    
          
  
}//抢夺成功，修改被抢者的公主信息
else{
    var query = new AV.Query(AV.User);
    query.get(robedUserId).then(function(post) {
        var totalCoin=post.get('coin');
        var curItemList=post.get('curItemListDic');
        var cacheStr=post.get('userCache');
        
        if(typeof(cacheStr) == "undefined")
            cacheStr="";
        if(typeof(curItemList) == "undefined")
            curItemList="";
        
        var newCacheStr="";
        var strs=new Array([]); 
        if(cacheStr!==""&&typeof(cacheStr) !== "undefined"){
            strs=cacheStr.split("*");
            if(parseInt(strs.length)>parseInt(10)){
                for(var i=0;i<strs.length;i++){
                    var newItemList="";
                    var lastNum=parseInt( parseInt(strs.length)-8);
                    if(parseInt(i)<lastNum){
                        
                       var dataStrs=strs[i].split(",");
                       var itemId=0;
                        var itemNum=0;
                        
                       for(var j=0;j<dataStrs.length;j++){
                           
                           if(dataStrs[j].match("coinNum")!==null)
                           {
                               var coinNum=parseInt(dataStrs[j].split(":")[1]);
                               if(coinNum>0)
                                    totalCoin+=coinNum;
                            }
                            if(dataStrs[j].match("itemId")!==null)
                                itemId=parseInt(dataStrs[j].split(":")[1]);
                            if(dataStrs[j].match("itemNum")!==null)
                                itemNum=parseInt(dataStrs[j].split(":")[1]);
                          
                       }//检查一个cachedata，获得coin和item数据
                       if(itemId>0){
                           var itemStrs=curItemList.split(",");
                           for(var n=0; n<itemStrs.length;n++){
                               if(itemStrs[n].match(itemId)!==null){
                                var curItemNum=parseInt(itemStrs[n].split(":")[1]); 
                                curItemNum+=itemNum;
                                newItemList+=(","+itemId+":"+curItemNum);  
                               }//id 相同，修改数量
                               else
                               newItemList+=(","+itemStrs[n]);
                           }
                           
                        if(newItemList.substring(0, 1) == "*")
                            newItemList= newItemList.substring(1); 
                        post.set('curItemListDic',newItemList);//修改物件
                       }//如果物件有物件序号，修改curItemList
                       
                       
                        
                    }else
                    newCacheStr+=("*"+strs[i]);
                    
                }   
                post.set('coin',totalCoin);//修改金币
                console.log(' 00  totalCoin: '+ totalCoin);
            }
            else
                newCacheStr=cacheStr;
        }else
            console.log('抢夺失败 cacheStr: '+ cacheStr);
            
        newCacheStr+= "*"+robAgeinPay;
        if(newCacheStr.substring(0, 1) == "*")
            newCacheStr= newCacheStr.substring(1);
        post.set('userCache',newCacheStr);
        //onsole.log('抢夺失败再次抢夺时间: '+ AV.Cloud.getServerDate（）);
        post.save();
        
        //console.log('抢夺失败再次抢夺给对方金币: '+ newCacheStr);

        }, function (error) {
      });
    
    
}//抢夺失败再次抢夺，给被抢者返回抢夺者的支付金币











})


/////
//更新评论
AV.Cloud.define('UpdateComment', function(request, response) {
var table=request.params.table;
var page=request.params.page;
console.log(' table' + table + ' page.'+page);
 
 var query = new AV.Query(table);
 query.skip(parseInt(page) *10);
  query.limit(10);
  query.find({
    success: function(results) {
      var sum = 0;
      var commentArray=new Array([]);
      for (var i = 0; i < results.length; ++i) {
          
          commentArray.unshift(results[i].get(["comment"]));
          console.log(commentArray.length);
      }
      response.success(commentArray);
    },
    error: function() {
      response.error('搜索失败');
    }
  });
  
})

///////
//创建地图
AV.Cloud.define('CreateMap', function(request, response) {
var landObjectId=request.params.landObjectId;
var mapObjectId=request.params.mapObjectId;
console.log(' landObjectId' + landObjectId + ' mapObjectId.'+mapObjectId);

var query2 = new AV.Query('AllMapData');
query2.get(mapObjectId).then(function(post) {
    var id=post.get('ID');
    var mapName='map'+id;
    post.set('name',mapName);
    post.save({
    success: function(result) {
        console.log(' result name: ' +mapName );
        response.success(mapName);
    },
    error: function() {
      response.error('搜索失败778');
    }
  });
    console.log(' map name: ' +  post.get('name') );
   
});

//根据新建的地图objectId。修改地图的名称。



})


//回应评论需求：求购，支持，出售等
AV.Cloud.define('responeComment', function(request, response) {
var commentId=request.params.commentId;
var askerId=request.params.requestUserId;
var resiverId=request.params.responeUserId;


var paramsJson={id:commentId};
	AV.Cloud.run("GetComment",paramsJson).then(function(comment) {
    var type=comment.get('type');
    var itemId=comment.get('itemId');
    var itemNum=comment.get('itemNum');
    var coinNum=comment.get('coinNum');
    var content=comment.get('content');
    var isRespond=comment.get('isRespond');
    comment.set('isRespond',true);
    redisClient.setAsync(redisCommentKey(resiverId), JSON.stringify(comment)).catch(console.error);//修改状态
    
    if(isRespond===false){    
		//接受者直接返回cache数据。同步修改接受者相关数据
		console.log('get comment data ' +itemId+ '  '+itemNum);
				
		paramsJson={id:resiverId};
		AV.Cloud.run("GetUser",paramsJson).then(function(resiver){			
			var cacheStr=resiver.get('userCache');
			if(typeof(cacheStr) === "undefined")
				cacheStr="";
			
			var sign=1;
			var sign2=1;

			if(type==1||type==3)
				sign=-1;
			if(type==1)
				sign2=0;
			if(type==2)
				sign2=-1;
			//接受者
				//请求支援，购买，给接收者减少请求物件,出售，给接收者增加物件
				//出售，给接受者减少金币，购买，给接受者增加金币

			var itemNum1=sign*itemNum;
			var coinNum1=sign2*coinNum;

				 
			var userIcon=resiver.get('userIcon');
			var nickname=resiver.get('nickname');
			var myDate=new Date();
			var dateStr=myDate.toLocaleString();
			dateStr= dateStr.replace(",","");

			var mType=-1;
			if(type==2)
				mType=3;
			if(type==3)
				mType=2;//如果对方是购买。接受方反应的是出售。如果对方是无偿支持请求。接受方是无偿支持
			var typeStr="\"type\":"+mType;
			var contentStr="\"content\":\""+content+"\"";
			var itemIdStr="\"itemId\":"+itemId;
			var itemNumStr="\"itemNum\":"+itemNum1;
			var coinNumStr="\"coinNum\":"+coinNum1;
			var userIconStr="\"userIcon\":"+userIcon;//暂时这样。后面由客户端统一修改吧
			var nicknameStr="\"nickname\":\""+nickname+"\"";//暂时这样。后面由客户端统一修改吧
			var userObjIdStr="\"userObjId\":\""+askerId+"\"";
			var dateStrStr="\"dateStr\":\""+dateStr+"\"";
		
			cacheStr+="*{"+typeStr+","+contentStr+","+coinNumStr+","+itemIdStr+","+itemNumStr+","
			+userIconStr+","+nicknameStr+","+userObjIdStr+","+dateStrStr+"}";
			if(cacheStr.substring(0, 1) == "*")
					cacheStr= cacheStr.substring(1);
			resiver.set('userCache',cacheStr);
			
			
			var coin=resiver.get('coin');
			var curItemListDic=resiver.get('curItemListDic');
			var newItemListStr="";
			coin+=coinNum1;
			resiver.set('coin',coin); //修改金币数量 
			
			if(typeof(curItemListDic) === "undefined")
				curItemListDic="";
			var itemStrs=curItemListDic.split(",");
			if(curItemListDic!==""){
				var hasItem=false;
				for(var m=0;m<itemStrs.length;m++){
					var itemStr=itemStrs[m];
					//console.log(' 222222222 itemStr  : ' +itemStr);
					if(typeof(itemStr) !== "undefined"&&itemStr!==""){
						var hasedItemId=parseInt(itemStr.split(":")[0]);
						var hasedItemNum=parseInt(itemStr.split(":")[1]);
						if(parseInt(hasedItemId)==itemId){
							hasItem=true;
							hasedItemNum+=itemNum1;
							itemStr=hasedItemId+":"+hasedItemNum;
							//console.log(itemNum+'  ********* 2222222222 hasItem  : ' +  hasedItemNum );
						}//如果有同id的。叠加
					}
					newItemListStr+=","+itemStr;//重新做itemListStr
				}
				if(hasItem===false){
					newItemListStr+=","+itemId+":"+itemNum1;//全新的直接加后面
					
				}
				
				
			}else{
				if(itemNum1>0)
					newItemListStr=itemId+":"+itemNum1;
			}
			if(newItemListStr.substring(0, 1) == ",")
				newItemListStr= newItemListStr.substring(1);
			resiver.set('curItemListDic',newItemListStr); //修改物件数量 
			
			//以上直接在服务端修改接受者的相关数据信息
			
			
			//以下请求者数据处理
			var paramsJson2={id:askerId,needCache:false};
			AV.Cloud.run("GetUser",paramsJson2).then(function(asker){
			//请求者数据处理
				
				var requesetCommentData=asker.get('requesetCommentData');
				if(typeof(requesetCommentData) !== "undefined"){
					
					var commentDataStrs=requesetCommentData.split("*");
					var newRequesetCommentData = "";
			
					
					for(var i=0;i<commentDataStrs.length;i++){
						if(commentDataStrs[i].indexOf(comment.id)>=0){
							var dataStrs=commentDataStrs[i].split(",");
							var newCommentData="";
							for(var j=0;j<dataStrs.length;j++)
							{
								var dataStr=dataStrs[j].split(":");
								if(dataStr.length==2)
								{
									if(dataStr[0].indexOf("isRespond")!=-1){
										if(dataStr[1].indexOf("false")!=-1){
											dataStr[1]="true}";
											dataStrs[j]=dataStr[0]+":"+dataStr[1];
											}
			
									}
								}
								newCommentData+=","+dataStrs[j];
							}
							if(newCommentData.substring(0, 1) == ",")
								newCommentData= newCommentData.substring(1);
							
							//遍历满足条件的comment数据并修改
							//console.log('responeComment type: ' +  type+" itemId "+itemId+"  itemNum "+itemNum+"  coinNum "+ coinNum+" isRespond "+isRespond);
							
							newRequesetCommentData+="*"+newCommentData;
						}else
							newRequesetCommentData+="*"+commentDataStrs[i];
							
					}
					if(newRequesetCommentData.substring(0, 1) == "*")
						newRequesetCommentData= newRequesetCommentData.substring(1);
						
					asker.set('requesetCommentData',newRequesetCommentData);//修改用户requesetCommentData
					 
					
				}
				
				var oriCacheStr=asker.get('userCache');
				if(typeof(oriCacheStr) === "undefined")
					oriCacheStr="";
				console.log(typeof(oriCacheStr)+'  oriCacheStr: ' +oriCacheStr);
				
				var cacheStr="";
				var sign=1;
				var sign2=1;

				if(type==1||type==3)
					sign=1;//请求支援和购买状态，请求者添加物件
				else 
					sign=1;//都添加物件（之前为：其他情况，不进行物件处理）。在客户端根据情况再做判断 
					

				if(type==2)
					sign2=1;//出售，请求者加金币
				else
					sign2=0;//其他情况，为零
				//申请者
				//请求支援，购买，给申请者增加物件,其他情况不进行物件处理
				//出售，给申请者增加金币，其他情况金币都为零
					 
				itemNum2=sign*itemNum;
				coinNum2=sign2*coinNum;
				
				var typeStr="\"type\":"+type;
				var contentStr="\"content\":\""+content+"\"";
				var itemIdStr="\"itemId\":"+itemId;
				var itemNumStr="\"itemNum\":"+itemNum2;
				var coinNumStr="\"coinNum\":"+coinNum2;
				var userIconStr="\"userIcon\":"+resiver.get("userIcon")+"\"";
				var nicknameStr="\"nickname\":\""+resiver.get("nickname")+"\"";
				var userObjIdStr="\"userObjId\":\""+resiver.id+"\"";
				var dateStrStr="\"dateStr\":\""+dateStr+"\"";
			
				cacheStr="{"+typeStr+","+contentStr+","+coinNumStr+","+itemIdStr+","+itemNumStr+","
				+userIconStr+","+nicknameStr+","+userObjIdStr+","+dateStrStr+"}";				
				//var neworiCacheStr=fCreateCacheData（type,content,itemId,itemNum,coinNum,dateStr,userIcon,nickname,responeUserId,false）;
				oriCacheStr+="*"+cacheStr;
				if(oriCacheStr.substring(0, 1) == "*")
					oriCacheStr= oriCacheStr.substring(1);
				asker.set('userCache',oriCacheStr); 
				
				
				
				redisClient.getAsync(redisUserKey(asker.id)).then(function(cachedUser) {
					if (cachedUser) {				  // 反序列化为 AV.Object
					//console.log('asker000 oriCacheStr ' +  oriCacheStr);	
					redisClient.setAsync(redisUserKey(asker.id), JSON.stringify(asker)).catch(console.error);					
					} else {
						//console.log('asker oriCacheStr ' +  oriCacheStr);	
						asker.save();
					}				
				});			
				//如果是当下在redis缓存的数据，更新数据。如果是从数据库提出的数据。保存到数据库
			
				
			});
			
			response.success(cacheStr);
			redisClient.setAsync(redisUserKey(resiverId), JSON.stringify(resiver)).catch(console.error);
		
		});
		
		
   
    }//如果isRespone为false。进行相关计算
    else{
         response.success("false");
    }
    
});

	
})

////////////////////
//评论支持与不支持点数设置
AV.Cloud.define('commentSupport', function(request, response) {
var commentId=request.params.commentId;
var support=request.params.support;
var userId=request.params.userId;
//console.log('commentSupport userId: '+ userId);

var paramsJson={id:commentId};
	AV.Cloud.run("GetComment",paramsJson).then(function(comment) {
    if(support.indexOf("True")!=-1)
        comment.increment('support', 1);
    else
        comment.increment('oppose', 1);     
	response.success(comment);
	redisClient.setAsync(redisCommentKey(commentId), JSON.stringify(comment)).catch(console.error);//更新redis缓存数据	 
  });   

redisClient.getAsync(redisUserKey(userId)).then(function(cachedUser) {
    if (cachedUser) {
      // 反序列化为 AV.Object	  
	  var newUser=new AV.User(JSON.parse(cachedUser), {parse: true});
		if(support.indexOf("True")!=-1)
			newUser.increment('zhan', 1);
		else
			newUser.increment('zhan', -1);
		redisClient.setAsync(redisUserKey(userId), JSON.stringify(newUser)).catch(console.error);
	  
    } else {
      new AV.Query(AV.User).get(userId).then(function(user) {
        if (user) {
			if(support.indexOf("True")!=-1)
				user.increment('zhan', 1);
			else
				user.increment('zhan', -1);				
			user.save();
        }     
      });
    }
  });

})
//////////////////
//更新地图评论数
AV.Cloud.define('updateMapEffectNum', function(request, response) {
var mapId=parseInt(request.params.mapId);
var comment=parseInt(request.params.comment);
var college=parseInt(request.params.college);

	var paramsJson={id:mapId};
	AV.Cloud.run("GetMap",paramsJson).then(function(map) {

    if(comment>0)
		map.increment('commentNum', 1); 
    if(college>0)
        map.increment('challengeNum', 1);   
    
	redisClient.setAsync(redisMapKey(mapId), JSON.stringify(map)).catch(console.error);//更新redis缓存数据
    //map.save();
    //console.log('map: '+ JSON.stringify(map));
	response.success(true);
    }, function (error) {
  });
  
})

//////////////
//获得用户自己的临时数据。只有加，没有减
AV.Cloud.define('GetCacheInformation', function(request, response) {
	var id=request.params.id;

	var paramsJson={id:id};
	AV.Cloud.run("GetUser",paramsJson).then(function(user){
        var totalCoin=user.get('coin');
        var curItemList=user.get('curItemListDic');
        var cacheStr=user.get('userCache');
        
        if(typeof(cacheStr) == "undefined")
            cacheStr="";
        if(typeof(curItemList) == "undefined")
            curItemList="";
        
        var newCacheStr="";
        var strs=new Array([]); 
        if(cacheStr!==""&&typeof(cacheStr) !== "undefined"){
            strs=cacheStr.split("*");
            for(var i=0;i<strs.length;i++){
                var newItemList="";

               var dataStrs=strs[i].split(",");
               var itemId=0;
               var itemNum=0;
                
               for(var j=0;j<dataStrs.length;j++){
                   
                   if(dataStrs[j].match("coinNum")!==null)
                   {
                       var coinNum=parseInt(dataStrs[j].split(":")[1]);
                       if(coinNum>0)
                            totalCoin+=coinNum;
                    }//修改coin数值
                    if(dataStrs[j].match("itemId")!==null)
                        itemId=parseInt(dataStrs[j].split(":")[1]);
                    if(dataStrs[j].match("itemNum")!==null)
                        itemNum=parseInt(dataStrs[j].split(":")[1]);
                  
               }//检查一个cachedata，获得coin和item数据
               if(itemId>0){
                   var itemStrs=curItemList.split(",");
                   for(var n=0; n<itemStrs.length;n++){
                       if(itemStrs[n].match(itemId)!==null){
                        var curItemNum=parseInt(itemStrs[n].split(":")[1]); 
                        curItemNum+=itemNum;
                        newItemList+=(","+itemId+":"+curItemNum);  
                       }//id 相同，修改数量
                       else
                       newItemList+=(","+itemStrs[n]);
                   }
                   
                if(newItemList.substring(0, 1) == ",")
                    newItemList= newItemList.substring(1); 
                user.set('curItemListDic',newItemList);//修改物件
               }//如果物件有物件序号，修改curItemList
                   
                
            }   
            user.set('coin',totalCoin);//修改金币
            console.log(' 00  totalCoin: '+ totalCoin);

        }
            
        user.set('userCache',"");
        response.success(true);
		redisClient.setAsync(redisUserKey(id), JSON.stringify(user)).catch(console.error);//更新redis缓存数据
        //user.save().then(function (data) {
        //    console.log(' GetCacheInformation is ok！！！: '  );
        //    response.success(cacheStr);
        //});
            
        
        //修改并保存玩家数据：coin，curItemListDick，cache
        
    });


})


///////////////
//更新用户核心数据修改:金币，门票 ，物件
AV.Cloud.define('UpdateUserData', function(request, response) {
var id=request.params.id;
var key=request.params.key;
var v=request.params.v;
var paramsJson={id:id};
AV.Cloud.run("GetUser",paramsJson).then(function(user)
 {
        if(key==="coin"){
            var coinNum=user.get('coin');
            coinNum+=v;
            user.set('coin',coinNum);
			//console.log(v+ ' final coin  : ' +  coinNum );
        }
        if(key==="robtick"){
            var robtick=user.get('robtick');
            robtick+=v;
            user.set('robtick',robtick);
			console.log(v+ ' final robtick  : ' +  robtick );
        }
        
        if(parseInt(parseInt(key)/1000)===1){
            var curItemListDic=user.get('curItemListDic');
            var itemId=parseInt(key);
            var itemNum=v;
            var newItemListStr="";

            if(typeof(curItemListDic) === "undefined")
                curItemListDic="";
            var itemStrs=curItemListDic.split(",");
            if(curItemListDic!==""){
				hasItem=false;
                for(var m=0;m<itemStrs.length;m++){
                    var itemStr=itemStrs[m];
                    //console.log(' 222222222 itemStr  : ' +itemStr);
                    if(typeof(itemStr) !== "undefined"&&itemStr!==""){
                        var hasedItemId=parseInt(itemStr.split(":")[0]);
                        var hasedItemNum=parseInt(itemStr.split(":")[1]);
                        if(parseInt(hasedItemId)==itemId){
                            hasItem=true;
                            hasedItemNum+=itemNum;
							if(hasedItemNum<=0)
								itemStr="";//物件少于零了。直接清掉
							else
								itemStr=hasedItemId+":"+hasedItemNum;
                            console.log(itemNum+'  ********* 2222222222 hasItem  : ' +  hasedItemNum );
                        }//如果有同id的。叠加
                    }
					if(itemStr!="")
						newItemListStr+=","+itemStr;//重新做itemListStr					
                }
				if(hasItem===false&&itemNum>0)
					newItemListStr+=","+itemId+":"+itemNum;//如果是新加的。直接添加
            }else{
                if(itemNum>0)
                    newItemListStr=itemId+":"+itemNum;
            }
            if(newItemListStr.substring(0, 1) == ",")
            newItemListStr= newItemListStr.substring(1);
			console.log(' final itemList  : ' +  newItemListStr );
           user.set('curItemListDic',newItemListStr); 
        }
        redisClient.setAsync(redisUserKey(id), JSON.stringify(user)).catch(console.error);//更新redis缓存数据
        response.success(true);
		//user.save();
        console.log('UpdateUserData........ ' +  key+"  "+v );
        
    });
})



////////////////////
//后宫的角色数据更新
AV.Cloud.define('HarmOpponentUpdate', function(request, response) {
var id=request.params.id;
var index=request.params.index;
var opponentStr=request.params.opponentStr;

//console.log('set harmOpponentList ......... '+opponentStr);
var cacheId=redisUserKey(id);
var paramsJson={id:id};
AV.Cloud.run("GetUser",paramsJson).then(function(user){
	console.log('set iuser ......... '+user.id);
	var harmOpponentList=user.get('harmOpponentList');
    var newOpponentList="";
    var datStrs=harmOpponentList.split('*');
    
    for(var i=0;i<datStrs.length;i++){
        var indexRefStr=":"+index+",";
        if(datStrs[i].match(indexRefStr)!==null)
            {
                newOpponentList+=("*"+opponentStr);
                 //console.log('set indexRefStr ......... '+opponentStr);
            }
        else
            newOpponentList+=("*"+datStrs[i]);
    }    
    if(newOpponentList.substring(0, 1) == "*")
       newOpponentList= newOpponentList.substring(1);
				
    //console.log('set harmOpponentList ......... '+newOpponentList);
    user.set('harmOpponentList',newOpponentList);
	redisClient.setAsync(cacheId, JSON.stringify(user)).catch(console.error);//更新redis缓存数据
	response.success(newOpponentList);

});

/*
var query1 = new AV.Query(AV.User);
query1.get(userId).then(function(user) {
    var harmOpponentList=user.get('harmOpponentList');
    var newOpponentList="";
    var datStrs=harmOpponentList.split('*');
    
    for(var i=0;i<datStrs.length;i++){
        var indexRefStr=":"+index+",";
        if(datStrs[i].match(indexRefStr)!==null)
            {
                newOpponentList+=("*"+opponentStr);
                 //console.log('set indexRefStr ......... '+opponentStr);
            }
        else
            newOpponentList+=("*"+datStrs[i]);
    }
    
    if(newOpponentList.substring(0, 1) == "*")
                newOpponentList= newOpponentList.substring(1);
    //console.log('set harmOpponentList ......... '+newOpponentList);

    user.set('harmOpponentList',newOpponentList);
    user.save({
    success: function(result) {
        //response.success(newOpponentList);
    },
    error: function() {
      response.error('搜索失败778');
    }
    });
    
    response.success(newOpponentList);
    
    }, function (error) {
});
*/

})


//删除地图
AV.Cloud.define('DeleteMap', function(request, response) {
var myDate = new Date();
var t_s=myDate.getTime();//转化为时间戳毫秒数
var refDate=new Date();//定义一个新时间
refDate.setTime(t_s+1000*60*60*24);//设置参考时间现在少一天

var query = new AV.Query('AllMapData');
var query1 = new AV.Query('AllChapterData');
var query2 = new AV.Query('AllLevelData');
var query3 = new AV.Query('AllScenceData');
var query4=new AV.Query('AllCommentData');



query.equalTo('isInDelete', true);//可
query.lessThan('updatedAt', refDate);//上次更新时间在一天前
query.find().then(function(todos) {
    for (var i = 0; i < todos.length; i++)
        {
          var todo = todos[i];
          
          var mapName=todo.get('name');
            query1.equalTo('map', mapName);
            query2.equalTo('map', mapName);
            query3.equalTo('map', mapName);
            query4.equalTo('map', mapName);
            
            DestroyDataBymapName (mapName);
        }
        
        AV.Object.destroyAll(todos);
    
});


        
        
        query1.find().then(function(results) {
        for (var i = 0; i < results.length; i++)
            {
              var todo = results[i];
            }
             AV.Object.destroyAll(results);
        },
        function (error) {
          response.error('删除章节失败');
      });
        
        query2.find().then(function(results) {
    for (var i = 0; i < results.length; i++)
        {
          var todo = results[i];
          todo.destroy();
        }
        AV.Object.destroyAll(results);
        
        
        
    },
    function (error) {
      response.error('删除关卡失败');
  });  

    query3.find().then(function(results) {
        for (var i = 0; i < results.length; i++)
            {
              var todo = results[i];
              todo.destroy();
            }
            AV.Object.destroyAll(results);
        },
        function (error) {
          response.error('删除场景失败');
      });
    
    query4.find().then(function(results) {
        for (var i = 0; i < results.length; i++)
            {
              var todo = results[i];
              todo.destroy();
            }
            
            AV.Object.destroyAll(results);
        },
        function (error) {
          response.error('删除评论失败');
      },
    function (error) {
      response.error('删除章节失败');
  });






function DestroyDataBymapName (mapName){
    var query1 = new AV.Query('AllChapterData');
    query1.equalTo('map', mapName);
    query1.find().then(function(results) {
        for (var i = 0; i < results.length; i++)
            {
              var todo = results[i];
            }
             AV.Object.destroyAll(results);
        },
        function (error) {
          response.error('删除章节失败');
      });
     
} 



 

})


/* 生成测试数据，创建 100 个 Post, 从 User 表中随机选择用户作为 author */
AV.Cloud.define('cretePost', function(request, response) {
  new AV.Query(AV.User).find().then(function(users) {
    AV.Object.saveAll(_.range(1, 100).map(function() {
      var post = new Post();
      post.set('author', _.sample(users));
      return post;
    })).then(function() {
      
    })
  });
});

AV.Cloud.define('delUser', function(request, response)  {
	var id=request.params.id;
	var coinNum=request.params.coin;
	redisClient.delAsync(redisUserKey(id)).then (
	function(){
		response.success(true);
	}
	); 
	
});

/* 查询角色 ******************************************************/
AV.Cloud.define('GetUser', function(request, response)  {
	var id=request.params.id;
	var needCache=request.params.needCache;
	console.log(id+'   needCache: ' + typeof(needCache));
	redisClient.getAsync(redisUserKey(id)).then(function(cachedUser) {
    if (cachedUser) {
      // 反序列化为 AV.Object	  
	  var newUser=new AV.User(JSON.parse(cachedUser), {parse: true});
		response.success(newUser);
	  //redisClient.ttl(redisUserKey(id), function(err, data){
		//  console.log('I live for this long yet: ' + data);});
		//过期时间
	  
    } else {
      new AV.Query(AV.User).get(id).then(function(user) {
        if (user) {		
			if(typeof(needCache)!=="boolean"){
				redisClient.setAsync(redisUserKey(id), JSON.stringify(user)).catch(console.error);//将数据加到redis缓存
				redisClient.saddAsync("userIds",redisUserKey(id));//用户id序号集合
				//redisClient.smembersAsync("userIds").then(function(idsStrs){
				//	console.log('GetUser  userIds ......... length '+idsStrs.length);
				//});
				
				//添加各种排名
				
				//redisClient.expire(redisUserKey(id),30);//设置过期
				
				user.set("onLine",true);
				user.save();//设置在线状态
			}
			//如果没有第二个参数。直接把数据更新到redis 缓存上。如果第二个参数有，表示仅为查询数据库。不做处理
		  response.success(user);
        }else
		response.success(null);//失败返回无
     
      });
    }
  });
	

});

var Comment = AV.Object.extend('AllCommentData');
//////查询评论
AV.Cloud.define('GetComment', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisCommentKey(id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
		if (cachedData) {
		  // 反序列化为 AV.Object	  
		  var newObj=new Comment(JSON.parse(cachedData), {parse: true});
		  response.success(newObj);
		} else {
		  new AV.Query(Comment).get(id).then(function(avObj) {
			if (avObj) {
			  // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("commentIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("commentIds").then(function(idsStrs){
			//console.log('GetUser  commentIds ......... length '+idsStrs.length);			
			//});	
			  
			response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}
  });
	

});

var Map = AV.Object.extend('AllMapData');
//清除地图数据
AV.Cloud.define('delMap', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisMapKey(100);
	console.log('delMap  cacheId ......... '+cacheId);	
	redisClient.delAsync(cacheId).then (
	function(){
		response.success(true);
	}
	); 
	
});

//////查询地图
AV.Cloud.define('GetMap', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisMapKey(id);
	console.log('GetMap  cacheId ......... '+cacheId);	
	redisClient.getAsync(cacheId).then(function(cachedData) {
    if (cachedData) {
	//console.log('GetMap   ......... '+cachedData);	
      // 反序列化为 AV.Object	  
	  var newObj=new Map(JSON.parse(cachedData), {parse: true});
	  response.success(newObj);
    }else {
		console.log('GetMap   ......... '+id);
	var query = new AV.Query(Map);
	query.equalTo('ID', id);
    query.first().then(function(avObj) {
        if (avObj) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			//redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("mapIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("mapIds").then(function(idsStrs){
			//console.log('GetMap  mapIds ......... length '+idsStrs.length);			
			//});	
			  
			  response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}
	
  });	

});
AV.Cloud.define('findallMap', function(request, response)  {
	
      new AV.Query(Map).find().then(function(results) {
		  for(var i=0;i< results.length;i++){
		  var avObj=results[i];		  
			var cacheId=redisMapKey(avObj.get("ID"));//使用地图ID作为id。
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,600);//设置过期
				
			redisClient.saddAsync("mapIds",cacheId);//id序号集合
				  
		  }
		  redisClient.smembersAsync("mapIds").then(function(idsStrs){
			console.log('GetMap  mapIds ......... length '+idsStrs.length);			
			});
		  response.success(results.length);
	});

});


//获得当前世界激活的地图数据
AV.Cloud.define('GetAllMap', function(request, response)  {

	var choicedMaps=new Array();//地图数组
	var n=0;
		redisClient.smembersAsync("mapIds").then(function(idsStrs){
		console.log('mapIds    ......... length '+idsStrs.length);	
			var promise = AV.Promise.as();
			_.each(idsStrs, function(cacheId){	
				promise = promise.then(function(){
					redisClient.getAsync(cacheId).then(function(cachedData) {
						if (cachedData) {
							  // 反序列化为 AV.Object	  
							  var newObj=new Map(JSON.parse(cachedData), {parse: true});
							  var updateAt=newObj.updateAt;
							  var challengeNum=newObj.get("challengeNum");
							  var commentNum=newObj.get("commentNum");
							  console.log(cacheId+'   clean *******---------********** '+cachedData);
							  choicedMaps.push(newObj);
							  /*
							  var myDate = new Date();
								var t_s=myDate.getTime();//转化为时间戳毫秒数
								var beforeDate=new Date();//定义一个新时间
								beforeDate.setTime(t_s-1000*60*60*24);// 设置昨天同一时刻
							  if(updateAt.getTime()>beforeDate.getTime()||challengeNum>10||commentNum>10){
								if(n<200)
									choicedMaps.push(newObj);
								n++;				
							  }
							  */
							  
							  //获得世界当前激活的。更新时间较近的。挑战次数较多的，评论数较多的地图
						}
						else{		
						console.log('clean ******************* ');
							console.log('clean cacheId '+cacheId);
							redisClient.sremAsync("mapIds",cacheId);
							}
							
					});
				});	
			});
			return promise;
		
		}).then(function(){
				console.log('choicedMaps ......... length '+choicedMaps.length);
				response.success(choicedMaps);
			
			});	
	
});


var Chapter = AV.Object.extend('AllChapterData');
//////查询章节
AV.Cloud.define('GetChapter', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisChapterKey(id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
    if (cachedData) {
      // 反序列化为 AV.Object	  
	  var newObj=new Chapter(JSON.parse(cachedData), {parse: true});
	  response.success(newObj);
    }else {
      new AV.Query(Chapter).get(id).then(function(avObj) {
        if (avObj) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("chapterIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("chapterIds").then(function(idsStrs){
			//console.log('GetChapter  chapterIds ......... length '+idsStrs.length);			
			//});	
			  
			  response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}		
  });	

});
var Scence = AV.Object.extend('AllScenceData');
//////查询场景
AV.Cloud.define('GetScence', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisScenceKey(id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
    if (cachedData) {
      // 反序列化为 AV.Object	  
	  var newObj=new Scence(JSON.parse(cachedData), {parse: true});
	  response.success(newObj);
    } else {
      new AV.Query(Scence).get(id).then(function(avObj) {
        if (avObj) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("scenceIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("scenceIds").then(function(idsStrs){
			//console.log('GetScence  scenceIds ......... length '+idsStrs.length);			
			//});	
			  
			  response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}
  });	

});

var Level = AV.Object.extend('AllLevelData');
//////查询关卡
AV.Cloud.define('GetLevel', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisLevelKey(id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
    if (cachedData) {
      // 反序列化为 AV.Object	  
	  var newObj=new Level(JSON.parse(cachedData), {parse: true});
	  response.success(newObj);
    }else {
      new AV.Query(Level).get(id).then(function(avObj) {
        if (avObj) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("levelIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("levelIds").then(function(idsStrs){
			//console.log('GetLevel  levelIds ......... length '+idsStrs.length);
			//});	
		  
			  response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}		
  });	

});

var Chat = AV.Object.extend('AllChatData');
//////查询对话
AV.Cloud.define('GetChat', function(request, response)  {
	var id=request.params.id;
	var cacheId=redisLevelKey(id);
	redisClient.getAsync(cacheId).then(function(cachedData) {
    if (cachedData) {
      // 反序列化为 AV.Object	  
	  var newObj=new Chat(JSON.parse(cachedData), {parse: true});
	  response.success(newObj);
    } else {
      new AV.Query(Chat).get(id).then(function(avObj) {
        if (avObj) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
			redisClient.setAsync(cacheId, JSON.stringify(avObj)).catch(console.error);
			redisClient.expire(cacheId,30);//设置过期
			redisClient.saddAsync("chatIds",cacheId);//id序号集合
			
			//redisClient.smembersAsync("chatIds").then(function(idsStrs){
			//console.log('GetMap  chatIds ......... length '+idsStrs.length);			
			//});	
					  
			  response.success(avObj);
			}else
			response.success(null);//失败返回无
			});
		}
  });	

});









/* 排行榜存储在 LeanCache 中的键名，按照当前日期存储为一个 ZSET，值是用户 ID */
function redisLeaderboardKey(time) {
  return 'leaderboard:' + moment(time).format('YYYYMMDD');
  
  
}





///////////////
//定时任务。持久化玩家数据
AV.Cloud.define('UpdateUserCloudCache', function(request, response) {
 redisClient.smembersAsync("userIds").then(function(idsStrs){
	 
		console.log('idsStrs.length .........   '+idsStrs.length);		
		var promise = AV.Promise.as();
		_.each(idsStrs, function(idStr) {
			console.log('UpdateUserCloudCache ......... .......................  ');
			promise = promise.then(function() {	
			console.log('UpdateUserCloudCache ......... idsStrs.length  '+idsStrs.length);			
			redisClient.getAsync(idStr).then(function(cachedUser) {
				if (cachedUser) {	
				  var newUser=new AV.User(JSON.parse(cachedUser), {parse: true});
					return newUser.save().then(function () {
						//console.log(moment().format('mm-SSS')+'*********************************  save user ');
						redisClient.srem("userIds",idStr );//删除集合元素
						redisClient.delAsync(idStr); 
					}, function (error) {
						return null;
					  if (error) {
						throw error;
					  }
					});
				}else{
					redisClient.srem("userIds",idStr );
					return redisClient.delAsync(idStr);
				}
			});
			  
			  //return result.destroy();
			});
		});
		  return promise;
		
	}).then(function(){
		response.success("UpdateUserCloudCache is ok！！！");
		
	});	

});

///////////////
//定时任务。持久化评论数据
AV.Cloud.define('UpdateCommentCloudCache', function(request, response) {
 redisClient.smembersAsync("commentIds").then(function(idsStrs){
	 console.log('UpdateCommentCloudCache ......... .......................  '+idsStrs.length);
		var promise = AV.Promise.as();
		_.each(idsStrs, function(idStr) {
			
			promise = promise.then(function() {	
			console.log('UpdateCommentCloudCache ......... idsStrs.length  '+idsStrs.length);			
			redisClient.getAsync(idStr).then(function(cachedUser) {
				if (cachedUser) {	
				  var newUser=new AV.User(JSON.parse(cachedUser), {parse: true});
					return newUser.save().then(function () {
						console.log(moment().format('mm-SSS')+' ********************************* save comment');
						redisClient.srem("userIds",idStr );//删除集合元素
						redisClient.delAsync(idStr); 
					}, function (error) {
						return null;
					  if (error) {
						throw error;
					  }
					});
				}else{
					redisClient.srem("userIds",idStr );
					return redisClient.delAsync(idStr);
				}
			});
			  
			  //return result.destroy();
			});
		});
		  return promise;
		
	}).then(function(){
		response.success("UpdateUserCloudCache is ok！！！");
		
	});	

});








AV.Cloud.define('SetUser', function(request, response) {
var userId=request.params.id;
var coinNum=request.params.coin;

	return fetchUserFromCache(userId).then(function(user) {
				user.set ('coin',coinNum);
				var userStr=JSON.stringify(user);
				redisClient.setAsync(redisUserKey(userId), userStr).catch(console.error);
				response.success(userStr);
				  
	});
});




/* 从缓存中读取一个 User, 如果没有找到则从云存储中查询 */
function fetchUserFromCache(id) {

  var cacheUserId=redisUserKey(id);
  return redisClient.getAsync(cacheUserId).then(function(cachedUser) {
    if (cachedUser) {
      // 反序列化为 AV.Object
	  console.log('fetchUserFromCache ......... 000000000000  ');
      return new AV.User(JSON.parse(cachedUser), {parse: true});
    } else {
      new AV.Query(AV.User).get(id).then(function(user) {
        if (user) {
          // 将序列化后的 JSON 字符串存储到 LeanCache		  
          redisClient.setAsync(redisUserKey(id), JSON.stringify(user)).catch(console.error);
		  //redisClient.set(redisUserKey(id), JSON.stringify(user));
		  console.log('fetchUserFromTable ......... 111111111111 ');
		  
        }
        return user;
      });
    }
  });
}

/* 从缓存中读取一组 User, 如果没有找到则从云存储中查询（会进行去重并合并为一个查询）*/
function fetchUsersFromCache(userIds) {
  // 先从 LeanCache 中查询
  return redisClient.mgetAsync(_.uniq(userIds).map(redisUserKey)).then(function(cachedUsers) {
    var parsedUsers = cachedUsers.map(function(user) {
      // 对 User（也就是 AV.Object）进行反序列化
      return new AV.User(JSON.parse(user), {parse: true});
    });

    // 找到 LeanCache 中没有缓存的那些 User
    var missUserIds = _.uniq(userIds.filter(function(userId) {
      return !_.find(parsedUsers, {id: userId});
    }));

    return Promise.try(function() {
      if (missUserIds.length) {
        // 从云存储中查询 LeanCache 中没有的 User
        return new AV.Query(AV.User).containedIn('objectId', missUserIds).find();
      } else {
        return [];
      }
    }).then(function(latestUsers) {
      if (latestUsers.length) {
        // 将从云存储中查询到的 User 缓存到 LeanCache, 此处为异步
        redisClient.msetAsync(_.flatten(latestUsers.map(function(user) {
          return [redisUserKey(user.id), JSON.stringify(user)];
        }))).catch(console.error);
      }

      // 将来自缓存和来自云存储的用户组合到一起作为结果返回
      return userIds.map(function(userId) {
        return _.find(parsedUsers, {id: userId}) || _.find(latestUsers, {id: userId});
      });
    });
  });
}

/* User 存储在 LeanCache 中的键名，值是经过 JSON 序列化的 AV.Object */
function redisUserKey(userId) {
  return 'users:' + userId;
}

function redisCommentKey(id) {
  return 'comment:' + id;
}
function redisMapKey(id) {
  return 'map:' + id;
}

function redisScenceKey(id) {
  return 'scence:' + id;
}
function redisChapterKey(id) {
  return 'chapter:' + id;
}
function redisLevelKey(id) {
  return 'level:' + id;
}

function redisChatKey(id) {
  return 'chat:' + id;
}




module.exports = AV.Cloud;